package com.ddpyjqtd.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.ddpyjqtd.utils.CamelCaseUtils;

/**
 * @Description: sql转换器，将bean对象通过反射转换成sql语句
 * 
 * @author: ddpyjqtd
 * @Date: 2019年3月25日
 *
 */
public class SqlConverter<T> {

	/**
	 * @Description: 将对象转换成sql语句
	 * 
	 * @author: ddpyjqtd
	 * @Date: 2019年3月25日
	 *
	 * @param bean
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 */
	public String getInsertSQL(T bean) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		StringBuilder sb = new StringBuilder();
		StringBuilder sbValue = new StringBuilder();
		// 1.取得对象的class
		Class<?> clazz = bean.getClass();
		// 2。取得类名，并转换成表名
		String tableName = clazz.getSimpleName();
		sb.append("INSERT INTO ").append(tableName.toUpperCase()).append("(");
		sbValue.append("");
		Method[] declaredMethods = clazz.getDeclaredMethods();
		String methodName = "";
		for (Method method : declaredMethods) {
			methodName = method.getName();
			if (!methodName.startsWith("get")) {
				continue;
			}
			// 字段名称
			String filedName = CamelCaseUtils.converter(methodName.substring(3));
			// 暴力破解
			method.setAccessible(true);
			// 获取调用方法
			Object value = method.invoke(bean);
			if (value == null) {
				continue;
			}
			if (value instanceof String) {
				sbValue.append(",'").append((String)value).append("'");
			} else if (value instanceof Integer) {
				sbValue.append(",").append((Integer)value);
			} else {
				System.out.println("暂不支持解析该类型属性：" + value);
				continue;
			}
			sb.append(filedName).append(",");
		}
		if (',' == sb.charAt(sb.length() -1)) {
			sb = new StringBuilder(sb.subSequence(0, sb.length() - 1));
		}
		if (sbValue.length() > 0) {
			sbValue = new StringBuilder(sbValue.substring(1));
		} else{
			throw new RuntimeException("对象无值，不能解析sql");
		}
		sbValue.append("); ");
		sb.append(") VALUES (" ).append(sbValue);
		// 3.取得属性与对应值，并转换成数据库字段与值
		// 4.拼接成sql进行返回

		return sb.toString();
	}
}
